package com.kaka.bus.engine.borrow.face;

import android.Manifest;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.kaka.bus.R;
import com.kaka.bus.base.BaseActivity;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.engine.home.main.limit.LimitActivity;
import com.kaka.bus.engine.other.DrainageActivity;
import com.kaka.bus.listener.Listener;
import com.kaka.bus.manager.Result;
import com.kaka.bus.manager.T;
import com.kaka.bus.util.U;
import com.kaka.bus.view.GlideOval;
import com.megvii.licensemanager.Manager;
import com.megvii.livenessdetection.LivenessLicenseManager;
import com.megvii.livenesslib.LivenessActivity;
import com.megvii.livenesslib.LivenessData;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.Map;

import butterknife.BindView;
import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.FlowableOnSubscribe;

/**
 * Created by zhangqi on 2016/10/11.
 */

public class FaceActivity extends BaseActivity<FacePresenter> implements FaceContract.View {


    @BindView(R.id.toolbar_back)
    ImageView mToolbarBack;
    @BindView(R.id.toolbar_name)
    TextView mToolbarName;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.iv_face)
    ImageView mIvFace;
    @BindView(R.id.tv_face_start)
    TextView mTvFaceStart;
    @BindView(R.id.btn_face_commit)
    AppCompatButton mBtnFaceCommit;

    private static final int PAGE_INTO_LIVENESS = 100;
    private String mResult;
    private boolean outTh = false;
    /**
     * 保存的文件
     */
    private String mUserName;
    private String mUserIdcard;
    private boolean mIsLiveness;
    private byte[] mImage_bests;
    private byte[] mImage_env;
    private String mUuid;
    private String mDelta;
    private RxPermissions mRxPermissions;
    @Override
    protected void initView() {
        super.initView();
        mToolbarName.setText("人脸识别");
        mToolbarBack.setOnClickListener(v -> finish());

        mRxPermissions = new RxPermissions(this);
    }

    @Override
    protected void initListener() {
        /**
         * 6.0摄像头权限校验
         */
        mIvFace.setOnClickListener(v -> {
            mRxPermissions.request(Manifest.permission.CAMERA)
                    .subscribe(aBoolean -> {
                        if(aBoolean)
                            goFace();
                    });
        });

        mBtnFaceCommit.setOnClickListener(v -> {
            if(outTh){
                showMessage("人脸识别失败超过三次,暂时无法进行认证!");
                return;
            }
            /**
             * 判断活体检测过吗
             */
            if(!mIsLiveness){
                showMessage("请先进行人脸识别!");
                return;
            }

            if(mImage_bests != null){
                mPresenter.commitPhotoData(mImage_bests,mImage_env,mDelta,getUserId(),getToken());
            }else{
                showMessage("请点击界面在次进行人脸识别!");
            }

        });
    }

    public void goFace() {
        runOnUiThread(() -> showDialog("联网授权中..."));

        mUuid = System.currentTimeMillis()+"";

        Flowable.create((FlowableOnSubscribe<Integer>) e -> {
            Manager manager = new Manager(this);
            LivenessLicenseManager licenseManager = new LivenessLicenseManager(this);
            manager.registerLicenseManager(licenseManager);
            manager.takeLicenseFromNetwork(mUuid);
            if (licenseManager.checkCachedLicense() > 0)
                e.onNext(1);
            else
                e.onNext(2);
        }, BackpressureStrategy.BUFFER)
                .compose(T.D())
                .subscribeWith(new Result<Integer>() {
                    @Override
                    protected void onSuccess(Integer result) {
                        dissDialog();
                        if(result == 1){
                            startActivityForResult(new Intent(FaceActivity.this, LivenessActivity.class),
                                    PAGE_INTO_LIVENESS);
                        }else if(result == 2){
                            showMessage("联网授权失败!请重试");
                        }
                    }
                });
    }

    @Override
    public void Faild(int type) {
        dissDialog();
        U.getSingleDialog(this,"温馨提示",type+"","确定",null).show();
    }

    @Override
    public String getUUID() {
        return mUuid;
    }

    @Override
    public void commitPhotoSuccess(HttpWrapper<String> wrapper) {
        startActivity(new Intent(this, LimitActivity.class));
    }

    @Override
    public void Faild(HttpWrapper<String> wrapper) {
        if(Constant.ID_CODE.equals(wrapper.code)){
            U.toDrainage(this, DrainageActivity.TYPE_REFUSE,Constant.REFUES);
        }else if(Constant.ERROR_CODE.equals(wrapper.code)){
          showMessage(wrapper.info);
        }else if("2001".equals(wrapper.code)){
            outTh = true;
            U.getSingleDialog(this, "温馨提示", wrapper.info, "关闭", this::finish).show();
        }else if(Constant.TOKEN_TIMEOUT.equals(wrapper.code)){
            U.tokenOut(this);
        }else{
            showMessage(wrapper.info);
        }
    }

    /**
     * 重新拍摄
     */
    public void reTakePhoto(String info) {
        U.getSlectDialog(this, "温馨提示", info, "取消", "重新认证", new Listener.OnNormalAlertDialogChooseClickListener() {
            @Override
            public void onLeft() {

            }

            @Override
            public void onRight() {
                goFace();
            }
        }).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PAGE_INTO_LIVENESS && resultCode == RESULT_OK) {
            LivenessData livenessData = (LivenessData) data.getSerializableExtra("result");
            Map<String, byte[]> images = livenessData.getImages();
            if(images != null && images.size() > 0){
                mImage_bests = livenessData.getImages().get("image_best");
                mImage_env = livenessData.getImages().get("image_env");
                mDelta = livenessData.getDelta();
            }

            showPhotoData(livenessData.getResID());
        }else{
            showMessage("取消");
        }
    }

    private void showPhotoData(int resultInfo) {
        if (resultInfo == R.string.verify_success) {
            doPlay(R.raw.meglive_success);
        } else if (resultInfo == R.string.liveness_detection_failed_not_video) {
            doPlay(R.raw.meglive_failed);
        } else if (resultInfo == R.string.liveness_detection_failed_timeout) {
            doPlay(R.raw.meglive_failed);
        } else if (resultInfo == R.string.liveness_detection_failed) {
            doPlay(R.raw.meglive_failed);
        } else {
            doPlay(R.raw.meglive_failed);
        }

        boolean isSuccess = resultInfo == R.string.verify_success;

        if(isSuccess){
            if(mImage_env != null)
                Glide.with(this)
                        .load(mImage_env).transform(new GlideOval(this))
                        .into(mIvFace);
            mTvFaceStart.setVisibility(View.GONE);
            mIsLiveness = true;
        }else{
            U.getSlectDialog(this, "温馨提示", "人脸识别失败,请重试", "取消", "确定", new Listener.OnNormalAlertDialogChooseClickListener() {
                @Override
                public void onLeft() {

                }

                @Override
                public void onRight() {
                    goFace();
                }
            }).show();
        }

    }
    private MediaPlayer mMediaPlayer = null;
    private void doPlay(int rawId) {
        if (mMediaPlayer == null)
            mMediaPlayer = new MediaPlayer();

        mMediaPlayer.reset();
        try {
            AssetFileDescriptor localAssetFileDescriptor = getResources()
                    .openRawResourceFd(rawId);
            mMediaPlayer.setDataSource(
                    localAssetFileDescriptor.getFileDescriptor(),
                    localAssetFileDescriptor.getStartOffset(),
                    localAssetFileDescriptor.getLength());
            mMediaPlayer.prepare();
            mMediaPlayer.start();
        } catch (Exception localIOException) {
            localIOException.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMediaPlayer != null) {
            mMediaPlayer.reset();
            mMediaPlayer.release();
        }
    }
    @Override
    protected boolean needFullScreen() {
        return true;
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_face;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

}
